from django.shortcuts import render
from .models import Lesson_note, Scheduling
from home.views import user_check
import markdown

# Create your views here.


def render_md(md: str):
    """渲染markdown"""
    html = markdown.markdown(
        md,
        extensions=[
            "markdown.extensions.extra",  # 额外插件
            "markdown.extensions.codehilite",  # 代码高亮
            "markdown.extensions.fenced_code",  # 代码格式化
            "markdown.extensions.toc",  # 目录
            "markdown.extensions.tables",  # 表格
            "markdown.extensions.attr_list",
            "mdx_math",
            "markdown.extensions.def_list",
            "markdown_katex",

        ],
        extension_configs={
            "mdx_math": {
                "enable_dollar_delimiter": True,  # 是否启用单美元符号（默认只启用双美元）
                "add_preview": True,  # 在公式加载成功前是否启用预览（默认不启用）
            },
            'markdown_katex': {
                'no_inline_svg': True,      # fix for WeasyPrint
                'insert_fonts_css': True,
            },
        },
    )

    return html


def get_note(request, id):
    """根据id获取上课记录"""
    context = user_check(request)
    note = Lesson_note.objects.filter(id=id)
    if note:
        note = note[0]
        note.title = f"{note.title}"
        context["title"] = note.title + "-课堂记录"
        note.note = render_md(note.note)
        print("after render:",note.note)
        note.stu_names = "，".join([str(i.real_name) for i in note.user.all()])
        context["note"] = note
        return render(request, "service/note.html", context=context)
    else:
        context["message_danger"] = "抱歉，没找到这条记录。"
        return render(request, "home/userhome.html", context=context)


def get_notice(request, id):
    """根据id获取排课记录"""
    context = user_check(request)
    notice = Scheduling.objects.filter(id=id)
    if notice:
        notice = notice[0]
        notice.title = f"《{notice.title}》课程预告"
        context["title"] += notice.title
        context["title"] += "-课程预告"
        notice.notice = render_md(notice.notice)
        notice.stu_names = "，".join([str(i.real_name)
                                    for i in notice.user.all()])
        context["notice"] = notice
        return render(request, "service/notice.html", context=context)
    else:
        context["message_danger"] = "抱歉，没找到这条记录。"
        return render(request, "home/userhome.html", context=context)
